package info.batcloud.fanli.core.service.impl;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import info.batcloud.fanli.core.entity.CommissionItem;
import info.batcloud.fanli.core.helper.SvgHelper;
import info.batcloud.fanli.core.repository.CommissionItemRepository;
import info.batcloud.fanli.core.service.CommissionItemService;
import info.batcloud.fanli.core.service.CommissionItemSharePicGenService;
import info.batcloud.fanli.core.service.UrlMappingService;
import info.batcloud.fanli.core.service.UserCommissionItemShareService;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.URLEncoder;

@Service
public class CommissionItemSharePicGenServiceImpl implements CommissionItemSharePicGenService {

    private Configuration configuration = new Configuration(Configuration.VERSION_2_3_27);

    @Inject
    private CommissionItemService commissionItemService;

    @Inject
    private CommissionItemRepository commissionItemRepository;

    @Inject
    private UserCommissionItemShareService userCommissionItemShareService;

    @Inject
    private UrlMappingService urlMappingService;

    @PostConstruct
    public void init() {
        configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), ""));
    }

    @Override
    public String genSharePicSvgXml(long itemId, long userId, String picUrl) {
        Template template = null;
        try {
            template = configuration.getTemplate("commission-item-share-pic.svg.ftlh");
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringWriter writer = new StringWriter();
        try {
            int titleRowLength = 30;
            CommissionItem ci = commissionItemRepository.findOne(itemId);
            String url =
                    userCommissionItemShareService.findUserCommissionItemShareUrl(itemId, userId);
            CommissionItemShareSvgVo svgModel = new CommissionItemShareSvgVo();
            svgModel.setPrice(ci.getPrice());
            svgModel.setUrl(URLEncoder.encode(url, "utf8"));
            svgModel.setQrCodeUrl(urlMappingService.getQrcodeUrl(svgModel.getUrl()));
            svgModel.setOriginPrice(ci.getOriginPrice());
            svgModel.setCouponValue(ci.getCouponValue());
            svgModel.setTitle(ci.getTitle());
            svgModel.setEconPlatName(ci.getEcomPlat().getTitle());
            svgModel.setPicUrl(StringUtils.isNotBlank(picUrl) ? picUrl : ci.getPicUrl());
            StringBuilder sb = new StringBuilder();
            float currentLength = 2f;
            for (int i = 0; i < ci.getTitle().length(); i++) {
                char c = ci.getTitle().charAt(i);
                if (isChinese(c)) {
                    currentLength += 2;
                } else {
                    currentLength += 1.5;
                }
                sb.append(c);
                if (currentLength >= titleRowLength) {
                    if (StringUtils.isBlank(svgModel.getTitleRow1())) {
                        svgModel.setTitleRow1(sb.toString());
                        sb = new StringBuilder();
                        currentLength = 0;
                    } else {
                        svgModel.setTitleRow2(sb.toString());
                        break;
                    }
                }
            }
            if (StringUtils.isBlank(svgModel.getTitleRow2())) {
                svgModel.setTitleRow2(sb.toString());
            }
            template.process(svgModel, writer);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return writer.toString();
    }

    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;
    }

    @Override
    public void genSharePic(long itemId, long userId, String picUrl, OutputStream os) {
        String svg = this.genSharePicSvgXml(itemId, userId, picUrl);
        try {
            SvgHelper.convertToJpg(svg, os, 800f, 1080f);
        } catch (TranscoderException e) {
            e.printStackTrace();
        }
    }

    public static class CommissionItemShareSvgVo {

        private String title;
        private String titleRow1;
        private String titleRow2;
        private Float price;
        private Float originPrice;
        private String econPlatName;
        private Float couponValue;
        private String url;
        private String qrCodeUrl;
        private String picUrl;

        public String getQrCodeUrl() {
            return qrCodeUrl;
        }

        public void setQrCodeUrl(String qrCodeUrl) {
            this.qrCodeUrl = qrCodeUrl;
        }

        public String getTitleRow1() {
            return titleRow1;
        }

        public void setTitleRow1(String titleRow1) {
            this.titleRow1 = titleRow1;
        }

        public String getTitleRow2() {
            return titleRow2;
        }

        public void setTitleRow2(String titleRow2) {
            this.titleRow2 = titleRow2;
        }

        public String getEconPlatName() {
            return econPlatName;
        }

        public void setEconPlatName(String econPlatName) {
            this.econPlatName = econPlatName;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Float getPrice() {
            return price;
        }

        public void setPrice(Float price) {
            this.price = price;
        }

        public Float getOriginPrice() {
            return originPrice;
        }

        public void setOriginPrice(Float originPrice) {
            this.originPrice = originPrice;
        }

        public Float getCouponValue() {
            return couponValue;
        }

        public void setCouponValue(Float couponValue) {
            this.couponValue = couponValue;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }
    }
}
